package com.by.auto.token;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class TokenTemplate {

    @Autowired
    TokenProperties tokenProperties;

    /**
     * 生成token、
     */
    public String generateToken(Map<String,?> payload){
        return JWT.create()
                .withHeader(getHeader())
                .withExpiresAt(getExireDate())
                .withPayload(payload)
                .sign(Algorithm.HMAC256(tokenProperties.getSecret()));
    }

    /**
     * 验证token
     */
    public ValidResult validToken(String token){
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(tokenProperties.getSecret())).build();
        DecodedJWT decodedJWT = null;
        try{
            decodedJWT = jwtVerifier.verify(token);
        } catch (JWTDecodeException e){
            return new ValidResult(0,"token无效",null);
        } catch (TokenExpiredException e){
            return new ValidResult(0,"token已过期",null);
        }
        return new ValidResult(1, "token有效", decodedJWT.getClaims());
    }


    Map getHeader(){
        Map map = new HashMap<>();
        map.put("typ","jwt");
        map.put("alg","HmacSHA256");
        return map;
    }

    /**
     * 1分钟有效期
     */
    Date getExireDate(){
        long time = System.currentTimeMillis() + tokenProperties.getValidTime();
        Date date = new Date(time);
        return date;
    }
}
